package IBBB.network.sendmessage;
import IBBB.model.WordStockMessage;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class send_query_word_stock extends send_String {
    public WordStockMessage getWordStockMessage() {
        return wordStockMessage;
    }

    Map<String, String> map = new LinkedHashMap<>();
    {
        map.put("cet4", "四级真题词汇");
        map.put("cet6", "六级真题词汇");
        map.put("kaoyan", "考研英语基础");
        map.put("toefl", "托福词汇");
        map.put("ielts", "雅思词汇");
    }
    WordStockMessage wordStockMessage;
    public send_query_word_stock(String ip) {
        super(ip);
        target_message = "queryDictionaryAll";
    }

    @Override
    public Void call() {

        Socket client = new Socket();
        try {
            client.connect(message_socket, 3000);
        } catch (Exception e) {
            updateMessage("timeout");
            return null;
        }


        try (ObjectOutputStream write = new ObjectOutputStream(client.getOutputStream())) {
            try (ObjectInputStream reader = new ObjectInputStream(client.getInputStream())) {
                write.writeObject(target_message);
                Map<String, Integer> wordsInfo = (HashMap<String, Integer>) reader.readObject();
                Map<String, Integer> newMap = new HashMap<>();
                for (Map.Entry<String, Integer> item: wordsInfo.entrySet()) {
                    newMap.put(map.get(item.getKey()), item.getValue());
                }
                wordStockMessage = new WordStockMessage(newMap);
                client.close();
                updateMessage("success");
            }
        } catch (Exception e) {
            updateMessage("wrong");
        }
        return null;
    }
}
